package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public class P398RandomPickIndex {
    public static void main(String[] args) {
        Solution solution = new P398RandomPickIndex().new Solution(new int[5]);

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        HashMap<Integer, List<Integer>> map = new HashMap<>();
        Random random = new Random();
        public Solution(int[] nums) {
            int index = 0;
            for (int num : nums) {
                final int i = index;
                map.compute(num, (integer, integers) -> {
                    if (integers == null) {
                        integers = new ArrayList<>();
                    }
                    integers.add(i);
                    return integers;
                });
                index++;
            }
        }

        public int pick(int target) {
            List<Integer> integers = map.get(target);
            if (integers.size() == 1) {
                return integers.get(0);
            }
            int size = integers.size();
            int i = random.nextInt(size);
            return integers.get(i);
        }
    }

/**
 * Your Solution object will be instantiated and called as such:
 * Solution obj = new Solution(nums);
 * int param_1 = obj.pick(target);
 */
//leetcode submit region end(Prohibit modification and deletion)

}